#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: dev_jenkins.py 
@version:
@time: 2022/04/02 
"""
import requests.utils
from requests import session
from bs4 import BeautifulSoup

import re

from TapDevops.CI.settings.dev_setting import DevJenkinsSetting


class DevJenkins(DevJenkinsSetting):
    session = None
    set_cookie = None
    project_name = None

    def __init__(self, project_name):
        """
        :param project_name: daas1 | daas2
        """
        if project_name not in ['daas1', 'daas2', 'dfs']:
            raise
        self.project_name = project_name
        self._runs_url = self.runs_url.get(project_name)
        self._daas_url = self.daas_url.get(project_name)
        if self.session is None:
            self.session = session()
        self.get_token()

    def dev_jenkins_request(self, method, url, **kwargs):
        while True:
            try:
                response = self.session.request(
                    method=method,
                    url=url,
                    headers=self.headers,
                    **kwargs
                )
                return response
            except Exception as e:
                print(e)

    def get_token(self):
        self.dev_jenkins_request(
            'POST',
            self.login_url,
            data=self.login_data
        )
        self.set_cookie = requests.utils.dict_from_cookiejar(
            self.session.cookies
        )
        list_string = [f"{k}={v}" for k, v in self.set_cookie.items()]
        self.headers = {"Cookie": list_string[0]}

    def get_runs(self):
        if self._runs_url:
            response = self.dev_jenkins_request(
                'GET', self._runs_url
            )
            return response.json()
        raise

    def get_git_change(self, build_number):
        url = f'{self._daas_url}{build_number}'
        response = self.dev_jenkins_request(
            'GET', url
        )
        return response.text

    def get_build_parameters(self, build_number):
        url = f'{self._daas_url}{build_number}/parameters'
        response = self.dev_jenkins_request(
            'GET',
            url
        )
        return response.text

    def get_console_text(self, build_number):
        url = f'{self._daas_url}{build_number}/consoleText'
        response = self.dev_jenkins_request(
            'GET',
            url
        )
        return response.text

    def get_docker_image(self, build_number):
        text = self.get_console_text(build_number)
        response = re.findall(self.harbor_regex, text)
        if response:
            return response[0][:-1]

    def get_build_useful_info(self):
        build_record = self.get_runs()
        all_build_useful_info = []
        for one_build_record in build_record:
            one_build_record_useful_info = dict()
            one_build_record_useful_info['build_url'] = self._daas_url
            one_build_record_useful_info['project_name'] = self.project_name
            one_build_record_useful_info["build_number"] = one_build_record["id"]
            one_build_record_useful_info["status"] = one_build_record["status"]
            one_build_record_useful_info["images"] = self.get_docker_image(one_build_record["id"])
            one_build_record_useful_info["stages"] = one_build_record["stages"]
            one_build_record_useful_info["user"] = self.get_user(one_build_record["id"])
            one_build_record_useful_info["at"] = self.get_at_people(one_build_record["id"])
            all_build_useful_info.append(one_build_record_useful_info)
        return all_build_useful_info

    def get_commit_info(self, build_number):
        html = self.get_git_change(build_number)
        soup = BeautifulSoup(html, features='html.parser')
        result = soup.find_all('ol')
        result = list(result)
        if result is []:
            return result
        result = re.findall(r"<li[^>]*>(?:[^<]+<[^li])+li>", str(result))
        t1 = []
        for i in result:
            # 替换<li>为空
            res_list = i.replace("<li>", "")
            # 替换</li>为空
            res_list = res_list.replace("</li>", "")
            # 将\n替换为
            # res_list = res_list.replace("\n", "</li>end")
            res_list = res_list.split("\n")
            res_list = res_list[0]
            t1.append(res_list)
        t2 = [str(t1.index(i) + 1) + "." + i for i in t1]
        LineFeed = "\n"
        t3 = LineFeed.join(t2)
        return t3

    def get_user(self, build_number):
        html = self.get_git_change(build_number)
        soup = BeautifulSoup(html, features='html.parser')
        result = soup.find_all('a')
        result = list(result)
        if result is []:
            return result
        result = re.findall(r"<a href=\"/user/[^>]*>(?:[^<]+<[^a])+a>", str(result))
        # split <
        raw = result[0].split('<')[1]
        # split >
        raw2 = raw.split('>')[1]
        return raw2

    def get_at_people(self, build_number):
        """
        获取飞书通知需要关注的人
        :param build_number:
        :return:
        """
        html = self.get_build_parameters(build_number)
        soup = BeautifulSoup(html, features="html.parser")
        res = soup.find_all("input")
        if len(res) == 19:
            split_str = str(res[-1]).split(" ")
            return split_str[-1].split("\"")[1]
        else:
            return None

    def _get_build_branch_info_daas1(self, build_number):
        html = self.get_git_change(build_number)
        soup = BeautifulSoup(html, features="html.parser")
        res = soup.find_all("li")
        res = list(res)
        res = re.findall(r"<li[^>]*>(?:[^<]+<[^li])+li>", str(res))
        t1 = res[-4:]
        t2 = []
        for i in t1:
            # 替换<li>为空
            res_list = i.replace("<li>", "")
            # 替换</li>为空
            res_list = res_list.replace("</li>", "")
            t2.append(res_list)
        t3 = {}
        t3["DAAS_BRANCH"] = t2[0]
        t3["APIG_BRANCH"] = t2[1]
        t3["TICDC_BRANCH"] = t2[2]
        t3["TAPDATA_AGENT_BRANCH"] = t2[3]
        t4 = []
        for k, v in t3.items():
            t4.append(f"{k}: {v}")
        LineFeed = "\n"
        t5 = LineFeed.join(t4)
        return t5

    def _get_build_branch_info_daas2(self, build_number):
        html = self.get_git_change(build_number)
        soup = BeautifulSoup(html, features="html.parser")
        res = soup.find_all("li")
        res = list(res)
        res = re.findall(r"<li[^>]*>(?:[^<]+<[^li])+li>", str(res))
        t1 = res[-6:]
        t2 = []
        for i in t1:
            # 替换<li>为空
            res_list = i.replace("<li>", "")
            # 替换</li>为空
            res_list = res_list.replace("</li>", "")
            t2.append(res_list)
        t3 = {}
        t3["DAAS_BRANCH"] = t2[0]
        t3["DAAS_CLOUD_BRANCH"] = t2[2]
        t3["DAAS_WEB_BRANCH"] = t2[1]
        t3["APIG_BRANCH"] = t2[3]
        t3["TICDC_BRANCH"] = t2[4]
        t3["TAPDATA_AGENT_BRANCH"] = t2[5]
        t4 = []
        for k, v in t3.items():
            t4.append(f"{k}: {v}")
        LineFeed = "\n"
        t5 = LineFeed.join(t4)
        return t5

    def _get_build_branch_info_dfs(self, build_number):
        html = self.get_git_change(build_number)
        soup = BeautifulSoup(html, features="html.parser")
        res = soup.find_all("li")
        res = list(res)
        res = re.findall(r"<li[^>]*>(?:[^<]+<[^li])+li>", str(res))
        t1 = res[-4:]
        t2 = []
        for i in t1:
            # 替换<li>为空
            res_list = i.replace("<li>", "")
            # 替换</li>为空
            res_list = res_list.replace("</li>", "")
            t2.append(res_list)
        t3 = {}
        print(t2)
        t3["DAAS_CLOUD_BRANCH"] = t2[0]
        t3["DAAS_BRANCH"] = t2[1]
        t3["DFS_WEB_BRANCH"] = t2[2]
        t4 = []
        for k, v in t3.items():
            t4.append(f"{k}: {v}")
        LineFeed = "\n"
        t5 = LineFeed.join(t4)
        return t5

    def get_build_branch_info(self, build_number):
        if self.project_name == 'daas1':
            return self._get_build_branch_info_daas1(build_number)
        elif self.project_name == 'daas2':
            return self._get_build_branch_info_daas2(build_number)
        elif self.project_name == 'dfs':
            return self._get_build_branch_info_dfs(build_number)
        raise


if __name__ == '__main__':
    T = DevJenkins('dfs')
    from pprint import pprint

    pprint(T.get_build_branch_info('19'))
